package com.alan.base.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class SimpleAdapter<T> extends RecyclerView.Adapter<CommonViewHolder> {

    private final List<T> list;
    private final Context mContext;

    private final SimpleView<T> factory;

    public SimpleAdapter(Context context, @NonNull SimpleView<T> factory, List<T> list) {
        this.mContext = context;
        this.list = new ArrayList<>();
        this.factory = factory;
        if(null!=list){
            this.list.addAll(list);
        }
    }

    @NonNull
    @Override
    public CommonViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new CommonViewHolder(this.factory.createView(viewType));
    }

    @Override
    public void onBindViewHolder(@NonNull CommonViewHolder holder, int position) {
        View itemView = holder.itemView;
        factory.setData(itemView, position, list.get(position));
    }

    @Override
    public int getItemCount() {
        return null == list ? 0 : list.size();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void refresh(List<T> list){
        this.list.clear();
        if(null!=list){
            this.list.addAll(list);
        }
        notifyDataSetChanged();
    }
}
